package com.example.androidapp2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.example.androidapp2.DbClasses.ItemCategoria;
import com.example.androidapp2.DbClasses.ItemIngresos;
import com.example.androidapp2.DbClasses.TotalCategoria;
import com.example.androidapp2.DbClasses.Utils;
import com.xyzdesa.droidnomy.R;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

public class DbAdapter extends SQLiteOpenHelper {
	private static String DB_NAME = "DrNomy";	
	public static String DB_PATH = "/DroidNomy/";
	public static String AYUDAPATH = "Ayuda/";
	private static String IMAGES = "images/";
	public static String AYUDAP = "Ayuda.htm";
	private static String[] Archivos = new String[]{"MenuCate.png","MenuEntradas.png","PantallaPpalMenuDet.png","PopUpModifica.png","PopUpPorcentajes.png"};


	private SQLiteDatabase myDataBase; 
	private Context myContext;

	public DbAdapter(Context context,Resources r) throws IOException {		
		super(context, DB_NAME, null, 1);
		myContext = context;
		CopiarBaseInicial(r);
	}

	public void CopiarBaseInicial(Resources r) throws IOException
	{		
		AssetManager assetManager = r.getAssets();
		File sdCard, directory,file = null;

		if (Environment.getExternalStorageState().equals("mounted")) {
			sdCard = Environment.getExternalStorageDirectory();

			directory = new File(sdCard.getAbsolutePath() + DB_PATH);
			if(!directory.exists())
				directory.mkdirs();

			file = new File(sdCard.getAbsolutePath() + DB_PATH + DB_NAME);
			if(!file.exists()){
				File f = new File(Environment.getExternalStorageDirectory()+DB_PATH, DB_NAME);
				InputStream is = assetManager.open(DB_NAME);
				OutputStream os = new FileOutputStream(f, true);
				final int buffer_size = 1024 * 1024;
				byte[] bytes = new byte[buffer_size];
				for (;;)
				{
					int count = is.read(bytes, 0, buffer_size);
					if (count == -1)
						break;
					os.write(bytes, 0, count);
				}
				is.close();
				os.close();
			}
		}		
	}

	public void CopiarAyuda() throws IOException
	{
		AssetManager assetManager = myContext.getAssets();
		File sdCard, directory,file = null;

		if (Environment.getExternalStorageState().equals("mounted")) {
			sdCard = Environment.getExternalStorageDirectory();

			directory = new File(sdCard.getAbsolutePath() + DB_PATH);
			if(!directory.exists())
				directory.mkdirs();
			directory = new File(sdCard.getAbsolutePath() + DB_PATH + AYUDAPATH);
			if(!directory.exists())
				directory.mkdirs();
			directory = new File(sdCard.getAbsolutePath() + DB_PATH + AYUDAPATH + IMAGES);
			if(!directory.exists())
				directory.mkdirs();

			file = new File(sdCard.getAbsolutePath() + DB_PATH  + AYUDAPATH + AYUDAP);
			if(!file.exists()){
				File f = new File(Environment.getExternalStorageDirectory()+DB_PATH+AYUDAPATH,  AYUDAP);
				InputStream is = assetManager.open(AYUDAPATH + AYUDAP);
				OutputStream os = new FileOutputStream(f, true);
				final int buffer_size = 1024 * 1024;
				byte[] bytes = new byte[buffer_size];
				for (;;)
				{
					int count = is.read(bytes, 0, buffer_size);
					if (count == -1)
						break;
					os.write(bytes, 0, count);
				}
				is.close();
				os.close();
			}

			for (int i = 0; i < Archivos.length; i++) {
				file = new File(sdCard.getAbsolutePath() + DB_PATH + AYUDAPATH +IMAGES+Archivos[i]);
				if(!file.exists()){
					File f = new File(Environment.getExternalStorageDirectory()+DB_PATH+ AYUDAPATH +IMAGES, Archivos[i]);
					InputStream is = assetManager.open(AYUDAPATH +IMAGES+ Archivos[i]);
					OutputStream os = new FileOutputStream(f, true);
					final int buffer_size = 1024 * 1024;
					byte[] bytes = new byte[buffer_size];
					for (;;)
					{
						int count = is.read(bytes, 0, buffer_size);
						if (count == -1)
							break;
						os.write(bytes, 0, count);
					}
					is.close();
					os.close();
				}
			}

		}
	}

	public void createDataBase() throws IOException{

		boolean dbExist = checkDataBase();

		if(!dbExist){			
			this.getWritableDatabase();

			try {

				copyDataBase();

			} catch (IOException e) {

				throw new Error("Error copying database");

			}
		}

	}

	private boolean checkDataBase(){

		SQLiteDatabase checkDB = null;

		try{
			if (Environment.getExternalStorageState().equals("mounted")) {
				String sdCard = Environment.getExternalStorageDirectory().getPath();

				String myPath = sdCard + DB_PATH + DB_NAME;
				checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
			}
		}catch(SQLiteException e){
			throw e;
		}

		if(checkDB != null){
			checkDB.close();
		}

		return checkDB != null ? true : false;
	}

	private void copyDataBase() throws IOException{
		if (Environment.getExternalStorageState().equals("mounted")) {
			String sdCard = Environment.getExternalStorageDirectory().getPath();

			//Open your local db as the input stream
			InputStream myInput = myContext.getAssets().open(DB_NAME);

			// Path to the just created empty db
			String outFileName = sdCard + DB_PATH + DB_NAME;

			//Open the empty db as the output stream
			OutputStream myOutput = new FileOutputStream(outFileName);

			//transfer bytes from the inputfile to the outputfile
			byte[] buffer = new byte[1024];
			int length;
			while ((length = myInput.read(buffer))>0){
				myOutput.write(buffer, 0, length);
			}

			//Close the streams
			myOutput.flush();
			myOutput.close();
			myInput.close();
		}
	}

	public void openDataBase() throws SQLException{

		if (Environment.getExternalStorageState().equals("mounted")) {
			String sdCard = Environment.getExternalStorageDirectory().getPath();

			String myPath = sdCard + DB_PATH + DB_NAME;

			myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);			
		}
	}

	public void DeleteDataBase()
	{		
		File sdCard, directory,file = null;

		if (Environment.getExternalStorageState().equals("mounted")) {
			sdCard = Environment.getExternalStorageDirectory();

			directory = new File(sdCard.getAbsolutePath() + DB_PATH);
			if(directory.exists()){
				file = new File(sdCard.getAbsolutePath() + DB_PATH + DB_NAME);
				if(file.exists()){
					file.delete();
				}
			}
		}

	}

	@Override
	public synchronized void close() {

		if(myDataBase != null)
			myDataBase.close();

		super.close();

	}

	public int GetTotalMovimientos(String tipo)
	{				
		Cursor c = this.myDataBase.query("Movimientos", new String[]{"SUM(Valor) AS Total"},"tipo='"+tipo+"' AND Estado = 1" , null, null, null, null);
		c.moveToFirst();

		int x = c.getInt(c.getColumnIndex("Total"));
		c.close();

		return x;
	}

	public int GetTotalMovimientosMes(String tipo,String mes)
	{				
		Cursor c = this.myDataBase.query("Movimientos", new String[]{"SUM(Valor) AS Total"},"tipo='"+tipo+"' AND Estado = 1 AND SUBSTR(Fecha,3,6)='"+ mes +"'" , null, null, null, null);
		c.moveToFirst();

		int x = c.getInt(c.getColumnIndex("Total"));
		c.close();

		return x;
	}

	public int GetTotalMovimientosAnio(String tipo,String anio)
	{				
		Cursor c = this.myDataBase.query("Movimientos", new String[]{"SUM(Valor) AS Total"},"tipo='"+tipo+"' AND Estado = 1 AND SUBSTR(Fecha,5,4)='"+ anio +"'" , null, null, null, null);
		c.moveToFirst();

		int x = c.getInt(c.getColumnIndex("Total"));
		c.close();

		return x;
	}


	public List<String> GetFechasSpinner()
	{
		List<String> ls = new ArrayList<String>();
		Resources res = myContext.getResources();
		ls.add(res.getString(R.string.spnItemCate));
		String sql = "SELECT Fecha FROM Movimientos WHERE Estado = 1 AND Tipo = 'Eg'";
		Cursor c = this.myDataBase.rawQuery(sql, null);
		c.moveToFirst();
		if(c.getCount()>0){
			ls.add(c.getString(0).substring(4, 8));
			ls.add(c.getString(0).substring(2, 8).replace(c.getString(0).substring(2, 4), c.getString(0).substring(2, 4)+" - "));
			while(!c.isLast()) {
				c.moveToNext();
				if(!ls.contains(c.getString(0).substring(4, 8)))
					ls.add(c.getString(0).substring(4, 8));
				if(!ls.contains(c.getString(0).substring(2, 8).replace(c.getString(0).substring(2, 4), c.getString(0).substring(2, 4)+" - ")))
					ls.add(c.getString(0).substring(2, 8).replace(c.getString(0).substring(2, 4), c.getString(0).substring(2, 4)+" - "));
			}
		}

		return ls;
	}

	public int GetIngresoAutomatico()
	{
		String sql = "SELECT Valor FROM DataRef WHERE ControlNm = 'SalarioAutomatico'";
		Cursor c = this.myDataBase.rawQuery(sql, null);
		c.moveToFirst();
		String str = c.getString(0);
		c.close();

		if(!str.equals("false"))
			return Integer.parseInt(str);		

		return 0;
	}

	public String GetFechaUltimoIngreso()
	{
		String sql = "SELECT Valor FROM DataRef WHERE ControlNm = 'UltimoIngreso'";
		Cursor c = this.myDataBase.rawQuery(sql, null);
		c.moveToFirst();
		String str = c.getString(0);
		c.close();

		return str;
	}


	public List<TotalCategoria> GetTotalesPorCategoria()
	{
		String lang = Locale.getDefault().getLanguage();
		String where="";
		if(lang.equals("es"))
			where+=" AND (Language = 'es' OR Language IS null )";
		else
			where+="AND (Language = 'en' OR Language IS null )";

		List<TotalCategoria> ls = new ArrayList<TotalCategoria>();
		String sql = "SELECT D.Valor AS Desc,SUM(M.Valor) AS Total "+
				"FROM Movimientos M JOIN DataRef D "+
				"ON  M.Categoria=D.Codigo "+
				"WHERE D.ControlNm='spnCategorias' "+
				"AND M.Tipo='Eg' " +
				"AND M.Estado = 1 "+
				where +
				"GROUP BY M.Categoria";

		List<ItemCategoria> lsCat = this.GetCategorias("spnCategorias",false,false);		

		Cursor c = this.myDataBase.rawQuery(sql,null);
		if(c.getCount()>0){
			c.moveToFirst();			
			ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			while(!c.isLast()) {
				c.moveToNext();
				ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			}
		}		
		c.close();

		if(ls.size()<lsCat.size())
			for (ItemCategoria it : lsCat) {
				boolean esta = false;
				for (TotalCategoria ct :ls ) {
					if(ct.Descripcion.equals(it.Descripcion))
						esta = true;
				}
				if(!esta)
					ls.add(new TotalCategoria(it.Descripcion, 0));
			}

		return ls;
	}

	public List<TotalCategoria> GetTotalesPorCategoriaAnio(String anio)
	{
		String lang = Locale.getDefault().getLanguage();
		String where="";
		if(lang.equals("es"))
			where+=" AND (Language = 'es' OR Language IS null )";
		else
			where+="AND (Language = 'en' OR Language IS null )";
		where += "AND SUBSTR(Fecha,5,4)='"+ anio +"' ";

		List<TotalCategoria> ls = new ArrayList<TotalCategoria>();
		String sql = "SELECT D.Valor AS Desc,SUM(M.Valor) AS Total "+
				"FROM Movimientos M JOIN DataRef D "+
				"ON  M.Categoria=D.Codigo "+
				"WHERE D.ControlNm='spnCategorias' "+
				"AND M.Tipo='Eg' " +
				"AND M.Estado = 1 "+
				where +
				"GROUP BY M.Categoria";

		List<ItemCategoria> lsCat = this.GetCategorias("spnCategorias",false,false);		

		Cursor c = this.myDataBase.rawQuery(sql,null);
		if(c.getCount()>0){
			c.moveToFirst();			
			ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			while(!c.isLast()) {
				c.moveToNext();
				ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			}
		}		
		c.close();

		if(ls.size()<lsCat.size())
			for (ItemCategoria it : lsCat) {
				boolean esta = false;
				for (TotalCategoria ct :ls ) {
					if(ct.Descripcion.equals(it.Descripcion))
						esta = true;
				}
				if(!esta)
					ls.add(new TotalCategoria(it.Descripcion, 0));
			}

		return ls;
	}

	public List<TotalCategoria> GetTotalesPorCategoriaMes(String mes)
	{
		String lang = Locale.getDefault().getLanguage();
		String where="";
		if(lang.equals("es"))
			where+=" AND (Language = 'es' OR Language IS null )";
		else
			where+="AND (Language = 'en' OR Language IS null )";
		where += "AND SUBSTR(Fecha,3,6)='"+ mes +"' ";

		List<TotalCategoria> ls = new ArrayList<TotalCategoria>();
		String sql = "SELECT D.Valor AS Desc,SUM(M.Valor) AS Total "+
				"FROM Movimientos M JOIN DataRef D "+
				"ON  M.Categoria=D.Codigo "+
				"WHERE D.ControlNm='spnCategorias' "+
				"AND M.Tipo='Eg' " +
				"AND M.Estado = 1 "+
				where +
				"GROUP BY M.Categoria";

		List<ItemCategoria> lsCat = this.GetCategorias("spnCategorias",false,false);		

		Cursor c = this.myDataBase.rawQuery(sql,null);
		if(c.getCount()>0){
			c.moveToFirst();			
			ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			while(!c.isLast()) {
				c.moveToNext();
				ls.add(new TotalCategoria(c.getString(0),c.getInt(1)));
			}
		}		
		c.close();

		if(ls.size()<lsCat.size())
			for (ItemCategoria it : lsCat) {
				boolean esta = false;
				for (TotalCategoria ct :ls ) {
					if(ct.Descripcion.equals(it.Descripcion))
						esta = true;
				}
				if(!esta)
					ls.add(new TotalCategoria(it.Descripcion, 0));
			}

		return ls;
	}

	public List<ItemIngresos> GetIngresos()
	{
		String lang = Locale.getDefault().getLanguage();
		String where="";
		if(lang.equals("es"))
			where+=" AND (Language = 'es' OR Language IS null ) ";
		else
			where+="AND (Language = 'en' OR Language IS null ) ";

		List<ItemIngresos> ls = new ArrayList<ItemIngresos>();
		ls.add(new ItemIngresos(0, 0,myContext.getResources().getString(R.string.strNuevoIngreso),""));

		String sql = "SELECT D.Valor, M.Valor,M.IdMovimiento, SUBSTR(Fecha,0,2) || '/'|| SUBSTR(Fecha,3,2) || '/'||SUBSTR(Fecha,5,4) "+
				"FROM Movimientos M LEFT JOIN DataRef D " +				
				"ON  M.Categoria=D.Codigo AND ControlNm = 'spnCategorias' "+
				where +
				"WHERE M.Estado = 1 " +
				"ORDER BY M.IdMovimiento DESC";			

		Cursor c = this.myDataBase.rawQuery(sql,null);
		if(c.getCount()>0){
			c.moveToFirst();
			ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),c.getString(0),c.getString(3)));
			while(!c.isLast()) {
				c.moveToNext();				
				ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),c.getString(0),c.getString(3)));
			}
		}		
		c.close();

		return ls;
	}

	public List<ItemIngresos> GetIngresosMes(String mes)
	{
		String lang = Locale.getDefault().getLanguage();
		String where="";
		if(lang.equals("es"))
			where+=" AND (Language = 'es' OR Language IS null ) ";
		else
			where+="AND (Language = 'en' OR Language IS null ) ";

		List<ItemIngresos> ls = new ArrayList<ItemIngresos>();
		ls.add(new ItemIngresos(0, 0,myContext.getResources().getString(R.string.strNuevoIngreso),""));

		String sql = "SELECT D.Valor, M.Valor,M.IdMovimiento, SUBSTR(Fecha,0,2) || '/'|| SUBSTR(Fecha,3,2) || '/'||SUBSTR(Fecha,5,4) "+
				"FROM Movimientos M LEFT JOIN DataRef D " +				
				"ON  M.Categoria=D.Codigo "+
				where +
				"WHERE M.Estado = 1 " +
				"AND SUBSTR(Fecha,3,6)='"+ mes +"' " +
				"ORDER BY M.IdMovimiento DESC";			

		Cursor c = this.myDataBase.rawQuery(sql,null);
		if(c.getCount()>0){
			c.moveToFirst();
			ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),c.getString(0),c.getString(3)));
			while(!c.isLast()) {
				c.moveToNext();				
				ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),c.getString(0),c.getString(3)));
			}
		}		
		c.close();

		return ls;
	}

	public List<ItemIngresos> GetIngresosAnio(String anio)
	{
		String lang = Locale.getDefault().getLanguage();
		String where="";
		if(lang.equals("es"))
			where+=" AND (Language = 'es' OR Language IS null ) ";
		else
			where+="AND (Language = 'en' OR Language IS null ) ";

		List<ItemIngresos> ls = new ArrayList<ItemIngresos>();
		ls.add(new ItemIngresos(0, 0,myContext.getResources().getString(R.string.strNuevoIngreso),""));

		String sql = "SELECT D.Valor, M.Valor,M.IdMovimiento, SUBSTR(Fecha,0,2) || '/'|| SUBSTR(Fecha,3,2) || '/'||SUBSTR(Fecha,5,4) "+
				"FROM Movimientos M LEFT JOIN DataRef D " +				
				"ON  M.Categoria=D.Codigo "+
				where +
				"WHERE M.Estado = 1 " +
				"AND SUBSTR(Fecha,5,4)='"+ anio +"' " +
				"ORDER BY M.IdMovimiento DESC";			

		Cursor c = this.myDataBase.rawQuery(sql,null);
		if(c.getCount()>0){
			c.moveToFirst();
			ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),c.getString(0),c.getString(3)));
			while(!c.isLast()) {
				c.moveToNext();				
				ls.add(new ItemIngresos(c.getInt(2),c.getInt(1),c.getString(0),c.getString(3)));
			}
		}		
		c.close();

		return ls;
	}


	public void UpdateIngreso()
	{

	}

	public void InsertMovimiento(int valor, String tipo, String fecha, String medio, int cate)
	{		
		ContentValues values = new ContentValues();
		values.put("Valor", valor);
		values.put("Tipo", tipo);
		values.put("Fecha", fecha);
		values.put("Medio", medio);
		values.put("Categoria", cate);
		values.put("Estado", 1);

		this.myDataBase.insert("Movimientos", null, values);
	}

	public void UpdateMovimientos(int id, int valor, int codCategoria)
	{
		String sql = "UPDATE Movimientos "+
				"SET Valor = "+valor+
				" ,Categoria = "+codCategoria+
				" WHERE IdMovimiento = "+id;

		this.myDataBase.execSQL(sql);		
	}


	public void UpdateMovimientosAInactivo(String condicion)
	{
		String sql = "UPDATE Movimientos "+
				"SET Estado = 0 "+
				"WHERE IdMovimiento in "+condicion;

		this.myDataBase.execSQL(sql);		
	}

	public void InactivarUltimo()
	{
		UpdateMovimientosAInactivo("(SELECT Max(IdMovimiento) " +
				"FROM Movimientos " +
				"WHERE Estado = 1 " +
				"AND Tipo = 'Eg')");
	}

	public void InactivarPorId(int id)
	{
		UpdateMovimientosAInactivo("("+id+")");
	}

	public void InactivarMes(String fecha)
	{
		String mes = fecha.substring(2, 8);
		UpdateMovimientosAInactivo("(SELECT IdMovimiento FROM Movimientos WHERE SUBSTR(Fecha,3,6)='"+ mes +"') AND Estado = 1");
	}

	public void InactivarAnual(String fecha)
	{
		String anio = fecha.substring(4, 8);
		UpdateMovimientosAInactivo("(SELECT IdMovimiento FROM Movimientos WHERE SUBSTR(Fecha,5,4)='"+ anio +"') AND Estado = 1");
	}

	public void InactivarTodos()
	{
		String sql = "UPDATE Movimientos "+
				"SET Estado = 0 ";

		myDataBase.execSQL(sql);		
	}

	public void SetSueldoAutomatico(String val)
	{
		String sql = "UPDATE DataRef " +
				"SET Valor = '"+val+"' " +
				"WHERE ControlNm = 'SalarioAutomatico'";
		myDataBase.execSQL(sql);
	}
	
	public void ClearSueldoAutomatico()
	{
		String sql = "UPDATE DataRef " +
				"SET Valor = 'false' " +
				"WHERE ControlNm = 'SalarioAutomatico'";
		myDataBase.execSQL(sql);
	}

	public boolean SetUltimoIngreso()
	{
		int Sueldo = GetIngresoAutomatico();
		if(this.GetTotalMovimientosMes("In",Utils.GetMesAnio())==0 && Sueldo == 0)
			return true;

		boolean abrePopUp = false;		
		String fecha = GetFechaUltimoIngreso();

		if(fecha != null){
			String mes = fecha.substring(2, 8);
			String hoy = Utils.GetFecha();
			if(!mes.equals(hoy.substring(2, 8)))				
				if(Sueldo>0)
					this.InsertMovimiento(Sueldo, "In", hoy, "EFT", 0);
				else 
					abrePopUp= true;
		}

		String sql = "UPDATE DataRef " +
				"SET Valor = '"+ Utils.GetFecha() +"' " +
				"WHERE ControlNm = 'UltimoIngreso'";
		myDataBase.execSQL(sql);

		return abrePopUp;
	}

	public void InsertarCategoria(String nombre)
	{
		String sql = "SELECT MAX(Codigo) FROM DataRef WHERE ControlNm = 'spnCategorias'";		
		Cursor c = myDataBase.rawQuery(sql, null); 
		c.moveToFirst();
		int cod = c.getInt(0)+1;
		c.close();

		ContentValues values = new ContentValues();		
		values.put("Codigo", cod);
		values.put("ControlNm", "spnCategorias");
		values.put("Valor", nombre);
		values.put("Estado",1);

		this.myDataBase.insert("DataRef", null, values);
	}

	public void ActivarCategoria(int cod)
	{
		String sql = "UPDATE DataRef " +
				"SET Estado = 1 " +
				"WHERE ControlNm='spnCategorias' AND " +
				"Codigo = "+cod;

		this.myDataBase.execSQL(sql);
	}


	public void InactivarCategoria(int cod)
	{
		String sql = "UPDATE DataRef " +
				"SET Estado = 0 " +
				"WHERE ControlNm='spnCategorias' AND " +
				"Codigo = "+cod;

		this.myDataBase.execSQL(sql);
	}

	public List<ItemCategoria> GetCategorias(String nombre, Boolean estado,Boolean addedCats)
	{			
		String lang = Locale.getDefault().getLanguage();
		String where = "ControlNm ='"+nombre+"' ";
		if(addedCats)
			where+="AND Language IS null ";
		else if(lang.equals("es"))
			where+="AND (Language = 'es' OR Language IS null ) ";
		else
			where+="AND (Language = 'en' OR Language IS null ) ";
		if(estado)
			where += "AND Estado=1";

		List<ItemCategoria> ls = new ArrayList<ItemCategoria>();
		Cursor c = this.myDataBase.query("DataRef", new String[]{"Codigo","Valor","Estado"},where, null, null, null, "Codigo");

		if(c.getCount()>0){
			c.moveToFirst();
			ls.add(new ItemCategoria(c.getInt(0), c.getString(1),c.getInt(2)));
			while(!c.isLast()) {
				c.moveToNext();
				ls.add(new ItemCategoria(c.getInt(0), c.getString(1),c.getInt(2)));
			}
		}
		c.close();

		return ls;
	}

	@Override
	public void onCreate(SQLiteDatabase arg0) {}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {}

}
